package com.yy.smartBI.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel 工具类
 */
@Slf4j
public class ExcelUtils {


    /**
     *  将Excel文件转换为CSV 格式
     *  @param file
     */
    public static String excelToCsv(MultipartFile file) {
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(file.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("文件转换失败",e);
        }
        //在对数据进行压缩
        StringBuilder stringBuilder = new StringBuilder();
        if(list == null) return "";
        //拿到表头 并加入
        List<String> collectHead = list.get(0).values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(collectHead,",")).append("\n");
        //遍历数据 并清洗不存在的值
        for (int i = 1; i < list.size(); i++) {
            List<String> collectData = list.get(i).values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(collectData,",")).append("\n");
        }
        return stringBuilder.toString();
    }
}
